<?php

// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------

namespace addons\Qrcode\controller;

use app\common\controller\Common;

require_once(dirname(dirname(__FILE__)) . "/sdk/phpqrcode.php");

/**
 * 二维码生成控制器
 * @package addons\Barcode\controller
 */
class Qrcode extends Common {
    
    public  $config = [];
    public function __construct(\think\Request $request = null) {
        parent::__construct($request);
        $this->config =  addons_config('qrcode');
    }

    /**
     * 生成二维码
     * @param string $text 二维码内容
     * @param string $file_path 二维码图片路径，默认生成在public/upload/qrcode目录下，图片名为“{md5}.png”
     * @acter  晓风<215628355@qq.com>    
     * 示例：
     * addons_action('Qrcode/Qrcode/generate', ['123456', APP_PATH . '/public/test.png']);
     */
    public function generate($text = '',$file_path = true,$config = []) {
       $outfile =  $file_path;   
       if(true === $outfile){
            $md5 = md5($text);
            $outfile =  ROOT_PATH ."public/qrcode/" . $md5 . ".png" ;
        }    
        if($outfile && file_exists($outfile)){
            return  str_replace("\\",'/',str_replace(realpath(ROOT_PATH . "public"), "", realpath($outfile)));
        }
        $tmpOutfile = $this->getCodeFile($text,$config);
        //如果不输出直接打印
        if (!$outfile) {
            header("Content-type: image/png");
            ob_end_clean();
            echo file_get_contents($tmpOutfile);
            die;
        }      
        copy($tmpOutfile, $outfile);
        unlink($tmpOutfile);         
        return  str_replace("\\",'/',str_replace(realpath(ROOT_PATH . "public"), "", realpath($outfile)));   
    }
    //获得二维码BASE64内容
    public function base64($text = '',$config = []) {          
        $tmpOutfile = $this->getCodeFile($text,$config);
        $content = file_get_contents($tmpOutfile);
        @unlink($tmpOutfile);
        return "data:image/png;base64,".base64_encode($content);            
    }
    //直接渲染二维码
    public function output($text = '',$config = []) {          
        $tmpOutfile = $this->getCodeFile($text,$config);
        header("Content-type: image/png");
        ob_end_clean();
        echo file_get_contents($tmpOutfile);
        @unlink($tmpOutfile);
        die;
    }
    
     /**
     * 生成二维码im对象
     * @param string $text 二维码内容
     * @acter  晓风<215628355@qq.com>     
     * 示例：
     * addons_action('Qrcode/Qrcode/getim', ['123456']);
     */
    public function getim($text = '') {
        //存放到临时文件
        $tmpOutfile =   RUNTIME_PATH .'/' . uniqid() . '.png';
        // 插件配置参数    
        \QRcode::png($text,$tmpOutfile,QR_ECLEVEL_L,3,0);   
        $im = imagecreatefromstring(file_get_contents($tmpOutfile));
        unlink($tmpOutfile);
        return $im;
    }

    private function getCodeFile($text = '',$config = []){
         // 插件配置参数
        $plugin_config = $this->config;
        //合并自定义配置
        $plugin_config = array_merge($plugin_config,$config);
        
        if ($plugin_config['back_color'] == '') {
            $plugin_config['back_color'] = 0xFFFFFF;
        } else {
            $plugin_config['back_color'] = hexdec($this->RGBToHex($plugin_config['back_color']));
        }
        if ($plugin_config['fore_color'] == '') {
            $plugin_config['fore_color'] = 0x000000;
        } else {
            $plugin_config['fore_color'] = hexdec($this->RGBToHex($plugin_config['fore_color']));
        }             
        
         //存放到临时文件
        $tempPath =  RUNTIME_PATH . '/tempcode';
        if ($tempPath && !is_dir($tempPath)) {
            mkdir($tempPath, 0777, true);
            chmod($tempPath, 0777);
        }       
        $tmpOutfile = $tempPath . '/' . uniqid() . '.png';
        $plugin_config['logo']= trim($plugin_config['logo']);
        \QRcode::png($text, $tmpOutfile, $plugin_config['level'], $plugin_config['size'], $plugin_config['margin'], false, $plugin_config['back_color'], $plugin_config['fore_color']);
        // 判断是否加logo
        if ($plugin_config['logo']) {
            $QR = imagecreatefromstring(file_get_contents($tmpOutfile));
            $logo = imagecreatefromstring(file_get_contents(realpath($plugin_config['logo'])));
            $QR_width = imagesx($QR); //二维码图片宽度
            $QR_height = imagesy($QR); //二维码图片高度
            $logo_width = imagesx($logo); //logo图片宽度
            $logo_height = imagesy($logo); //logo图片高度

            $logo_qr_width = $QR_width / 5;
            $scale = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width = ($QR_width - $logo_qr_width) / 2;
            //重新组合图片并调整大小
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
            // 生成带logo的二维码图片
            imagepng($QR, $tmpOutfile);
        }  
        return $tmpOutfile;
    }
    /**
     * 十六进制 转 RGB
     * @param  string $hexColor 16进制颜色值
     * @from http://blog.csdn.net/shaerdong/article/details/46805807
     * @return array RGB数组
     */
    function hex2rgb($hexColor) {
        $color = str_replace('#', '', $hexColor);
        if (strlen($color) > 3) {
            $rgb = array(
                'r' => hexdec(substr($color, 0, 2)),
                'g' => hexdec(substr($color, 2, 2)),
                'b' => hexdec(substr($color, 4, 2))
            );
        } else {
            $color = $hexColor;
            $r = substr($color, 0, 1) . substr($color, 0, 1);
            $g = substr($color, 1, 1) . substr($color, 1, 1);
            $b = substr($color, 2, 1) . substr($color, 2, 1);
            $rgb = array(
                'r' => hexdec($r),
                'g' => hexdec($g),
                'b' => hexdec($b)
            );
        }
        return $rgb;
    }

    /**
     * RGB转 十六进制
     * @param string $rgb RGB颜色的字符串 如：rgb(255,255,255);
     * @from http://blog.csdn.net/shaerdong/article/details/46805807
     * @return string
     */
    function RGBToHex($rgb) {
        $regexp = "/^rgb\(([0-9]{0,3})\,\s*([0-9]{0,3})\,\s*([0-9]{0,3})\)/";
        preg_match($regexp, $rgb, $match);
        array_shift($match);
        $hexColor = "0x";
        $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
        for ($i = 0; $i < 3; $i++) {
            $r = null;
            $c = $match[$i];
            $hexAr = array();
            while ($c > 16) {
                $r = $c % 16;
                $c = ($c / 16) >> 0;
                array_push($hexAr, $hex[$r]);
            }
            array_push($hexAr, $hex[$c]);
            $ret = array_reverse($hexAr);
            $item = implode('', $ret);
            $item = str_pad($item, 2, '0', STR_PAD_LEFT);
            $hexColor .= $item;
        }
        return $hexColor;
    }

}
